package com.cloud.handler;


import com.cloud.common.constants.CommonConstant;
import com.cloud.common.domain.response.BaseResponse;
import com.cloud.common.utils.JsonUtil;
import com.cloud.mq.base.core.CloudMQTemplate;
import com.cloud.platform.rocketmq.timedjob.TimeBasedJobMessage;
import com.cloud.scheduled.job.core.context.XxlJobHelper;
import com.cloud.scheduled.job.core.dto.ExecutorParamsDTO;
import com.cloud.scheduled.job.core.handler.annotation.XxlJob;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @description:
 * @author: zhou shuai
 * @date: 2022/2/18 16:47
 * @version: v1
 */
@Component
@Slf4j
public class MqJobExecutor {

    @Autowired
    private CloudMQTemplate cloudMQTemplate;

    /**
     * 定时任务发送MQ
     */
    @XxlJob(CommonConstant.CloudScheduledJob.EXECUTOR_HANDLER_NAME)
    public void mqJobHandler() {
        log.info("=====进入执行器:{}逻辑处理======", CommonConstant.CloudScheduledJob.EXECUTOR_HANDLER_NAME);
        String executorParams = XxlJobHelper.getJobParam();

        if (StringUtils.isBlank(executorParams)) {
            return;
        }

        log.info("executorParams:{}", executorParams);

        ExecutorParamsDTO executorParamsDTO = JsonUtil.toBean(executorParams, ExecutorParamsDTO.class);

        if (Objects.isNull(executorParamsDTO) || StringUtils.isEmpty(executorParamsDTO.getEventCode()) || Objects.isNull(executorParamsDTO.getLogId())) {
            return;
        }

        TimeBasedJobMessage timeBasedJobMessage = new TimeBasedJobMessage(executorParamsDTO.getLogId(), System.currentTimeMillis());
        BaseResponse<Object> sendResult = cloudMQTemplate.send(CommonConstant.CloudScheduledJob.SCHEDULED_JOB_TOPIC, executorParamsDTO.getEventCode(), timeBasedJobMessage);

        if (!sendResult.isSuccess()) {
            XxlJobHelper.handleFail();
        }

        XxlJobHelper.log("XXL-JOB发送RockrtMQ,Topic:{},eventCode:{},messageBody:{}", CommonConstant.CloudScheduledJob.SCHEDULED_JOB_TOPIC, executorParamsDTO.getEventCode(), JsonUtil.toString(timeBasedJobMessage));

        // default success
        XxlJobHelper.handleSuccess();
    }

}
